package com.qf.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.dto.PropertyDto;
import com.qf.dto.UserDto;
import com.qf.entity.Elefee;
import com.qf.entity.Owner;
import com.qf.entity.Property;
import com.qf.entity.User;
import com.qf.result.ResponseResult;
import com.qf.service.ElefeeService;
import com.qf.service.OwnerService;
import com.qf.service.PropertyService;
import com.qf.utils.BeanCopyUtils;
import com.qf.utils.MailUtil;
import com.qf.utils.PayUtil;
import com.qf.utils.Utils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/property")
@Slf4j
public class PropertyController {

    @Autowired
    ElefeeService elefeeService;

    @Autowired
    OwnerService ownerService;

    @Autowired
    PropertyService propertyService;

    @Autowired
    PayUtil payUtil;

    @Autowired
    MailUtil mailUtil;

    @PostMapping("/pay")
    public ResponseResult pay(@RequestBody Property property, HttpServletRequest request, HttpServletResponse response){
//        Double waterFee = waterfee.getWaterFee();
        Double fee = property.getFee();
        try {
            String alipay = payUtil.alipay(request, response, fee,property.getId());

            return ResponseResult.okResult(alipay);
        }catch (Exception e){
            return ResponseResult.errorResult(201,"支付失败");
        }
//        return ResultBean.FAIL();
    }

    @PostMapping("/pay/notify")
    public void notifyUrl(HttpServletRequest request) throws AlipayApiException {

        //先验签,
        Map<String, String> paramsMap = Utils.convertRequestParamsToMap(request); //将异步通知中收到的所有参数都存放到 map 中

        //System.out.println(paramsMap+"=========================");
        String sign = paramsMap.get("sign");

        String content = AlipaySignature.getSignCheckContentV1(paramsMap);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, payUtil.getALIPAY_PUBLIC_KEY(), "UTF-8"); // 验证签名
       // System.out.println(checkSignature+"====================");
//        boolean  signVerified = AlipaySignature.rsaCheckV1(paramsMap, payUtil.getAPP_PRIVATE_KEY(), "utf-8", "RSA2");  //调用SDK验证签名
        //验签成功 再根据支付修改订单状态
        if (checkSignature){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商家自身业务处理，校验失败返回failure
            //购买成功,修改数据库

            log.info("============================>验签中");

            UpdateWrapper<Owner> wrapper = new UpdateWrapper<>();
            Property user =propertyService.getById(Integer.parseInt(paramsMap.get("passback_params")));

            Integer ownId = user.getOwnId();
            Owner owner = ownerService.getById(ownId);

            String s = paramsMap.get("buyer_pay_amount");
            wrapper.set("total_property_fee",owner.getTotalPropertyFee()+Double.valueOf(s)).eq("id",ownId);
            ownerService.update(wrapper);

            UpdateWrapper<Property> wrapper1 = new UpdateWrapper<>();
            wrapper1.set("fee_status",1).eq("id",user.getId());
            propertyService.update(wrapper1);
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

    //同步回调
//    @GetMapping("/return")
//    public String returnUrl(){
////        charset=utf8&out_trade_no=83ca5d9d139c4a76bd537236b00b1233&method=alipay.trade.page.pay.return&total_amount=8888.00&sign=DfNvIBGmqA0gy0ftMyQcjPsjCgRq3sFQiov5Jg%2FKDM8mN5AxAD4uMeVoWhH5DCDnyc9Oh9QhUmLACSSyFIREbT0Zm9Qh7jSCubjE%2Bz0dqaWgRVmwcXFXoswW1nTjmxbnj4HxVGAsxGCT0iSNS3wz8g%2Ffm5DumTaTuWDBw5hhBAcBSggVLHgC5sT9E9SlcYfghA96%2FeSfMTyWcPD83gY8ND4xGZ6oGcav1L6NlpJlopSMAsSJLOb6jF3bumt%2Btjz5MqayI%2BypRxOcO48a26jJMFwgWBFa5i3riIGtzyA1%2Fqeasi%2BIgomMfMhQUX25heuSNgsprCmNUICckEsn6qVi%2BQ%3D%3D&trade_no=2023020722001490160501916870&auth_app_id=2021000121697951&version=1.0&app_id=2021000121697951&sign_type=RSA2&seller_id=2088621993967369&timestamp=2023-02-07+23%3A20%3A28
//        //@RequestParam("out_trade_no") String oid
//        return "success";//跳转前端页面显示；
//    }

    @GetMapping("/findAll")
    public ResponseResult findAll(String ownerName){
        return propertyService.findAll(ownerName);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable Integer id){
        return propertyService.delete(id);
    }

    @PostMapping("/add")
    public ResponseResult add(@Valid @RequestBody PropertyDto propertyDto){
        propertyDto.setCreateTime(new Date());
        return propertyService.add(BeanCopyUtils.copyBean(propertyDto.setId(null), Property.class));
    }

    //通过HouseId查询一条
//    @ApiOperation(value = "通过HouseId查询一条")
//    @GetMapping("/HouseId/{id}")
//    public ResponseResult selectOneByHouseId(@ApiParam(value = "HouseId",required = true,example = "1")@PathVariable("id") Integer id) {
//        return propertyService.selectOneByHouseId(id);
//    }

    @GetMapping("/findAllHouse")
    public ResponseResult findAllHouse(){
        return elefeeService.findAllHouse();
    }

    @GetMapping("/findOwnerByHouseId")
    public ResponseResult findOwnerByHouseId(String house){
        return elefeeService.findOwnerByHouseId(house);
    }


}
